package controllers

import (
	"encoding/json"
	"git.tmuyu.com.cn/beego/models"
	"git.tmuyu.com.cn/beego/service"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
	"strconv"
)

type MsgController struct {
	beego.Controller
}

func (c *MsgController) SendMsg() {
	Content := c.Ctx.Input.RequestBody
	data := models.SendData{}

	err := json.Unmarshal(Content, &data)
	if err != nil {
		c.Data["json"] = &models.Response{
			Code:    400,
			Data:    nil,
			Message: err.Error(),
		}
		c.ServeJSON()
		return
	}

	err2, errCode := service.FindOpenid(data)
	if err2 != nil {
		c.Data["json"] = &models.Response{
			Code:    errCode,
			Data:    nil,
			Message: err2.Error(),
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = &models.Response{
		Code:    200,
		Data:    nil,
		Message: "access",
	}
	c.ServeJSON()
	return
}

func (c *MsgController) SendIsSelfMsg() {

	var data models.SendData
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &data)
	if err != nil {
		logs.Warn("err:", err.Error())
	}
	err, errCode := service.FindSelfOpenid(data)
	if err != nil {
		c.Data["json"] = &models.Response{
			Code:    errCode,
			Data:    nil,
			Message: err.Error(),
		}
		c.ServeJSON()
	}
	c.Data["json"] = &models.Response{
		Code:    200,
		Data:    nil,
		Message: "access",
	}
	c.ServeJSON()

}

//获取openid列表
func (c *MsgController) GetOpenid() {
	var openids []models.CreatMsg
	//var limit models.Limits
	_limit := c.Input().Get("limit")
	limit, err := strconv.Atoi(_limit)
	if err != nil {
		limit = 1
	}

	openids = service.GetOpenid(limit)
	if openids == nil {
		c.Data["json"] = &models.Response{
			Code:    201,
			Data:    nil,
			Message: "success",
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = &models.Response{
		Code:    200,
		Data:    openids,
		Message: "success",
	}
	c.ServeJSON()
	return
}

func (c *MsgController) CreateSendMsg() {
	var CreatMsg models.CreatMsg
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &CreatMsg)
	if err != nil {
		logs.Warn("err:", err.Error())
	}
	if CreatMsg.Openid == "" {
		c.Data["json"] = &models.Response{
			Code:    405,
			Data:    nil,
			Message: "openid is null or \"\"",
		}
		c.ServeJSON()
	}
	err, errCode := service.CreateSendmsg(CreatMsg)
	if err != nil {
		c.Data["json"] = &models.Response{
			Code:    errCode,
			Data:    nil,
			Message: err.Error(),
		}
		c.ServeJSON()
	}
	c.Data["json"] = &models.Response{
		Code:    200,
		Data:    nil,
		Message: "access",
	}
	c.ServeJSON()
}
